package com.hc.conferencecheck.filters;

import com.hc.conferencecheck.entity.ResultMsg;
import com.hc.conferencecheck.entity.ResultStatusCode;
import com.hc.conferencecheck.utils.CustomMessageUtil;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于验证码发送间隔检测的过滤器
 * 拦截发送注册验证码、发送重置密码验证码
 */
//@WebFilter(filterName = "codeIntervalFilter", urlPatterns = {"/messageController/sendRegisterVerificationCode", "/messageController/sendEditPasswordVerificationCode"})
public class Filter1_CodeIntervalFilter implements Filter {
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Filter1_CodeIntervalFilter.class);

    @Override
    public void init(FilterConfig config) throws ServletException {
        logger.info("初始化验证码发送间隔过滤器");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        logger.info("进入验证码发送间隔过滤器");
        //获取存储上次发送时间的session
        HttpSession session = ((HttpServletRequest) request).getSession();
        Object lastSendTimeObj = session.getAttribute("lastSendTime");
        if (lastSendTimeObj == null) {
            //如果属性为null，说明是首次登陆或者已经超过限制时间,直接放行（发送验证码的时候存储发送时间）
            chain.doFilter(request, response);
        } else {
            //如果属性不为null，获取当前时间并判断和上次时间的间隔，如果没有一分钟，不允许再次发送；如果超过一分钟，可以发送（发送后要存储发送时间）
            String lastSendTimeStr = lastSendTimeObj.toString();
            Long lastSendTime = Long.valueOf(lastSendTimeStr);
            //获取当前时间
            long currentTime = System.currentTimeMillis() / 1000;
            //得到两次发送时间的间隔
            long interval = currentTime - lastSendTime;
            if (interval <= 60) {
                //两次间隔小于60s，不允许再次发送，返回自定义信息
                ResultMsg resultMsg = new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "验证码发送过于频繁");
                CustomMessageUtil.returnCustomMessage((HttpServletResponse) response, resultMsg);
            } else {
                //发送间隔符合要求，放行，发送验证码
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
    }

}
